<!--
 * @Description: zzb
 * @Version: 0.0.1
 * @Autor: zzb
 * @Date: 2022-06-28 15:23:55
 * @LastEditors: zzb
 * @LastEditTime: 2023-08-21 11:56:04
-->
<template>
  <div class="app-container">
    <div class="content-wrap" v-show="showSearch">
      <el-form
        :model="queryParams"
        size="small"
        ref="queryForm"
        :inline="true"
        @submit.native.prevent
      >
        <el-form-item label="文件名称" prop="keyword">
          <el-input
            v-model="queryParams.keyword"
            placeholder="请输入文件名称"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="文件类型" prop="fileType">
          <el-select
            v-model="queryParams.fileType"
            clearable
            placeholder="文件类型"
          >
            <el-option label="图片" value="images"> </el-option>
            <el-option label="视频" value="medias"> </el-option>
            <el-option label="其他" value="docs"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <el-row :gutter="10" class="m0 p0 grid-content">
      <el-col :span="1.5">
        <el-button
          size="mini"
          type="primary"
          plain
          icon="el-icon-plus"
          @click="handleUpload"
          v-hasPermi="['image:gallery:upload']"
          >上传文件</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleDelete"
          v-hasPermi="['system:role:remove']"
          v-if="false"
          >删除</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
        v-if="false"
      ></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="imgFileList">
      <el-table-column type="index" width="55" align="center" label="序号">
      </el-table-column>
      <el-table-column
        label="文件名"
        prop="fileName"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <i
            :class="
              scope.row.fileType == 'medias'
                ? 'el-icon-video-play'
                : scope.row.fileType == 'medias'
                ? 'el-icon-picture-outline'
                : 'el-icon-tickets'
            "
          ></i>

          <span
            style="margin-left: 10px; cursor: pointer"
            @click="getFileUrl(scope.row)"
          >
            {{ scope.row.fileName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="类型" width="150" :formatter="typeName" />
      <el-table-column label="文件大小" width="100" :formatter="fileSize" />
      <el-table-column
        label="所属站点"
        prop="roleSort"
        width="150"
        :formatter="siteFormat"
      />
      <el-table-column label="上传时间" prop="time" width="170" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="200"
      >
        <template slot-scope="scope">
          <el-tooltip
            class="item"
            effect="dark"
            :content="copyContent"
            placement="top"
          >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-share"
              v-clipboard:copy="scope.row.url"
              v-clipboard:success="handleCopySuccess"
              v-clipboard:error="handleCopyerror"
              v-on:mouseenter.native="handleLeave()"
              >复制链接</el-button
            >
          </el-tooltip>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['image:gallery:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog
      v-dialogDrag
      :title="title"
      :visible.sync="open"
      width="780px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      destroy-on-close
    >
      <el-form :model="form" label-width="80px" ref="ruleForm">
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属站点" prop="siteAlias" required>
              <el-select v-model="form.siteAlias" placeholder="请选择">
                <el-option
                  v-for="item in siteList"
                  :key="item.siteId"
                  :label="item.name"
                  :value="item.alias"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="文件列表" prop="file" required>
              <!-- <span>上传文件</span> -->
              <Uploader
                @input="onBigFileSuccess"
                :showFileList="true"
                :showDrop="true"
                :autoStart="false"
                :siteAlias="form.siteAlias"
                :accept="[
                  '.flv',
                  '.mp4',
                  '.wmv',
                  '.avi',
                  '.jpg',
                  '.jpeg',
                  '.png',
                  '.gif',
                  '.bmp',
                  '.jfif',
                  '.doc',
                  '.docx',
                  '.xls',
                  '.xlsx',
                  '.ppt',
                  '.pptx',
                  '.html',
                  '.htm',
                  '.js',
                  '.css',
                  '.txt',
                  '.pdf',
                  '.zip',
                  '.rar',
                ]"
                v-show="form.siteAlias"
              >
                选择文件<i class="el-icon-upload el-icon--right"></i>
              </Uploader>
              <span v-show="!form.siteAlias"
                ><font color="red">请先选择所属站点</font>
              </span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button @click="cancel">取 消</el-button> -->
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { pictureList, pictureRemove, pictureAdd } from "@/api/file/index";
import Uploader from "@/components/Uploader";
import { getToken } from "@/utils/auth";

import { mapState } from "vuex";
import { formatFileSize } from "@/utils";
export default {
  props: {
    siteList: {
      type: Array,
      default: () => {
        return [];
      },
    },
  },
  name: "File",
  data() {
    return {
      fileType: ["jpg", "png", "jpeg"],
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/image/gallery/upload", // 上传的图片服务器地址
      headers: {
        Authorization: getToken(),
      },
      copyContent: "复制到剪贴板",

      loading: false,
      //upload 的文件列表
      fileList: [],
      imgFileList: [],
      // 列表数量
      total: 0,
      //是否搜索
      showSearch: true,
      //查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: "",
        fileType: "",
      },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      form: {
        // 上传图片时 选择的 站点别名
        siteAlias: "",
      },
      filesForm: [], // 只用来存储分片上传成功的文件列表
      rules: {
        siteAlias: [
          {
            required: true,
            message: "请选择站点",
            trigger: ["change", "blur"],
          },
        ],
        file: [{ required: true, message: "请上传图片", trigger: "change" }],
      },
    };
  },
  components: { Uploader },
  computed: {
    ...mapState({
      userId: (state) => state.user.userId,
      city_name: (state) => state.user.city_name,
    }),
  },
  created() {
    if (this.city_name == "dwdt") {
      this.queryParams.fileType = "medias";
    }
    this.getList();
  },
  mounted() {},
  methods: {
    /** 获取文件列表 */
    getList() {
      this.loading = true;

      pictureList(this.queryParams).then((res) => {
        this.imgFileList = res.data.list;
        this.total = res.data.totalCount;
        this.loading = false;
      });
    },
    handleBeforeUpload(file) {
      console.log("file: ", file);
      // 校检文件类型
      if (!this.form.siteAlias) {
        this.msgError("所属站点不能为空");
        return false;
      }
      let fileExtension = "";
      if (file.name.lastIndexOf(".") > -1) {
        fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
      }
      const isTypeOk = this.fileType.some((type) => {
        if (file.type.indexOf(type) > -1) return true;
        if (fileExtension && fileExtension.indexOf(type) > -1) return true;
        return false;
      });
      if (!isTypeOk) {
        this.$message.error(
          `文件格式不正确, 请上传${this.fileType.join(" ， ")}格式文件!`
        );
        return false;
      }
    },
    handleDelete(row) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          pictureRemove(row.id).then((res) => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleUpload() {
      this.title = "上传图片";
      this.open = true;
      this.reset();
    },
    // 上传成功回调
    handleUploadSuccess(res) {
      console.log("res: ", res);
    },
    // 确认上传
    submitForm() {
      // this.filesForm.forEach((item) => {
      //   pictureAdd(this.filesForm).then((res) => {
      //     console.log("res: ", res);
      //   });
      // });
      let a = this.filesForm.map((item) => {
        return pictureAdd(item);
      });
      Promise.all(a).then(() => {
        this.open = false;
        this.getList();
        this.reset();
        this.fileList = [];
      });

      return;
      this.open = false;
      this.getList();
      this.reset();
      this.fileList = [];
    },
    // 电网动态大视频上传成功回调
    onBigFileSuccess(file) {
      console.log("file: onBigFileSuccess", file);
      console.log(UA);
      let obj = {
        ...file,
        userId: this.userId,
        belongTo: "person", //  person个人 communal公共
      };
      this.filesForm.push(obj);
    },
    // 上传进度回调
    onBigFileProgress(uploadPercentage) {},

    cancel() {},
    reset() {
      this.form = {
        siteAlias: "",
      };
      if (this.siteList.length == 1) {
        this.form.siteAlias = this.siteList[0].alias;
      }
      this.filesForm = [];
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleCopySuccess(row) {
      this.copyContent = "已复制";
    },
    handleCopyerror() {
      alert("Failed to copy texts");
    },
    handleLeave() {
      this.copyContent = "复制到剪贴板";
    },
    getFileUrl(item) {
      if (item.fileType == "docs") {
        this.$message({
          type: "error",
          message: "该文件不支持在线查看!",
        });
        return;
      }
      let href = item.url;
      window.open(href, "_blank");
    },
    typeName(row) {
      console.log("row.fileName: ", row.fileName);
      if (!row.fileName) return;
      let index = row.fileName.lastIndexOf(".") + 1;
      return row.fileName.slice(index).toLocaleUpperCase();
    },
    fileSize(row) {
      console.log("row: ", row);
      return formatFileSize(+row.fileSize);
      // return row.width + " * " + row.height;
    },
    siteFormat(row) {
      return this.selectDictLabel(
        this.siteList,
        row.siteAlias,
        "alias",
        "name"
      );
    },
  },
};
</script>
<style lang="scss" scoped>
.app-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.el-image__inner.el-image__preview {
  max-width: 28px;
  max-height: 28px;
  display: inline;
  vertical-align: middle;
}

.uploader-ui {
  display: unset;
}
</style>
